﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MetaCollection.Framework.Model;
using System.Reflection;

namespace MetaCollection.Framework.Security
{
	public static class RequiredAccessRights
	{
		/// <summary>
		/// Gets the rights on a method of sourceType.
		/// </summary>
		/// <param name="sourceType">Type of the source.</param>
		/// <param name="methodName">Name of the method.</param>
		/// <returns></returns>
		public static IDictionary<ItemTargets, AccessRights> GetRightsOnMethod(Type sourceType, string methodName)
		{
			IDictionary<ItemTargets, AccessRights> results = new Dictionary<ItemTargets, AccessRights>();
			if (sourceType != null)
			{
				MethodInfo mi = sourceType.GetMethod(methodName);
				if (mi != null)
				{
					RequiredAccessRightsAttribute[] rightAttributes = mi.GetCustomAttributes(typeof(RequiredAccessRightsAttribute), false) as RequiredAccessRightsAttribute[];
					foreach (RequiredAccessRightsAttribute attribute in rightAttributes)
					{
						results.Add(attribute.Targets, attribute.RequiredRights);
					}
				}
			}
			return results;
		}
		/// <summary>
		/// Gets the rights on a field of sourceType.
		/// </summary>
		/// <param name="sourceType">Type of the source.</param>
		/// <param name="fieldName">Name of the field.</param>
		/// <returns></returns>
		public static IDictionary<ItemTargets, AccessRights> GetRightsOnField(Type sourceType, string fieldName)
		{
			IDictionary<ItemTargets, AccessRights> results = new Dictionary<ItemTargets, AccessRights>();
			if (sourceType != null)
			{
				FieldInfo fi = sourceType.GetField(fieldName);
				if (fi != null)
				{
					RequiredAccessRightsAttribute[] rightAttributes = fi.GetCustomAttributes(typeof(RequiredAccessRightsAttribute), false) as RequiredAccessRightsAttribute[];
					foreach (RequiredAccessRightsAttribute attribute in rightAttributes)
					{
						results.Add(attribute.Targets, attribute.RequiredRights);
					}
				}
			}
			return results;
		}
	}
}
